package gupao.concurrency.threads;

public class VolatileSample1 {

    public static void main(String[] args){
        int threadCount = 10;
        VolatileImpl v = new VolatileImpl();
        for(int i = 0; i < threadCount; i++){
            new Thread(() -> {
                for( int k = 0; k < 20; k++){
                    v.incrementAndGet();
                    Utils.waitNanos(10000);
                }
            }).start();
        }
        while(Thread.activeCount() > 1){
            Thread.yield();
        }
        System.out.println(v.getX());
    }

    static class VolatileImpl{
        volatile long x = 0L;
        public long incrementAndGet() {
            x++;
            return x;
        }
        public void setX(long x) {
            this.x = x;
        }
        public long getX() {
            return x;
        }
    }

    static class NonVolatileImpl{
        long x = 0L;
        public long incrementAndGet() {
            long tmp = getX();
            tmp += 1;
            setX(tmp); //只有这一步是原子的
            return x;
        }
        public synchronized void setX(long x) {
            this.x = x;
        }
        public long getX() {
            return x;
        }
    }

}
